<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head profile="http://gmpg.org/xfn/11">
<meta name="verify-v1" content="GeXKtanER98tyl4cTdtBqKhayl5odjJIjPACPNxPlNY=">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="icon" type="image/png" href="http://akrabat.com/favicon.png">
<title>Returning JSON using the Accept header in ZF2  –   Rob Allen's DevNotes</title>

<link href="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/css.css" rel="stylesheet" type="text/css">

<meta name="readability-verification" content="gVhhHPJN2LhzPExSW85N9vxBRBGz9nmUErVYVLt7">
<meta name="generator" content="WordPress 3.5.1"> <!-- leave this for stats -->

<link href="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/css.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/style.css" type="text/css" media="screen">
<link rel="alternate" type="application/rss+xml" title="Rob Allen's DevNotes RSS Feed" href="http://akrabat.com/feed/">

<style type="text/css" media="screen">


</style>

<style type="text/css">/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for php
 * CSS class: , CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.php .de1, .php .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.php  {font-family:monospace;}
.php .imp {font-weight: bold; color: red;}
.php li, .php .li1 {font-weight: normal; vertical-align:top;}
.php .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.php .li2 {font-weight: bold; vertical-align:top;}
.php .kw1 {color: #b1b100;}
.php .kw2 {color: #000000; font-weight: bold;}
.php .kw3 {color: #990000;}
.php .kw4 {color: #009900; font-weight: bold;}
.php .co1 {color: #666666; font-style: italic;}
.php .co2 {color: #666666; font-style: italic;}
.php .co3 {color: #0000cc; font-style: italic;}
.php .co4 {color: #009933; font-style: italic;}
.php .coMULTI {color: #666666; font-style: italic;}
.php .es0 {color: #000099; font-weight: bold;}
.php .es1 {color: #000099; font-weight: bold;}
.php .es2 {color: #660099; font-weight: bold;}
.php .es3 {color: #660099; font-weight: bold;}
.php .es4 {color: #006699; font-weight: bold;}
.php .es5 {color: #006699; font-weight: bold; font-style: italic;}
.php .es6 {color: #009933; font-weight: bold;}
.php .es_h {color: #000099; font-weight: bold;}
.php .br0 {color: #009900;}
.php .sy0 {color: #339933;}
.php .sy1 {color: #000000; font-weight: bold;}
.php .st0 {color: #0000ff;}
.php .st_h {color: #0000ff;}
.php .nu0 {color: #cc66cc;}
.php .nu8 {color: #208080;}
.php .nu12 {color: #208080;}
.php .nu19 {color:#800080;}
.php .me1 {color: #004000;}
.php .me2 {color: #004000;}
.php .re0 {color: #000088;}
.php .ln-xtra, .php li.ln-xtra, .php div.ln-xtra {background-color: #ffc;}
.php span.xtra { display:block; }
</style><link rel="stylesheet" id="wp_geshi_wp-geshi-highlight-css" href="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/wp-geshi-highlight.css" type="text/css" media="all">
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://akrabat.com/xmlrpc.php?rsd">
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://akrabat.com/wp-includes/wlwmanifest.xml"> 
<link rel="prev" title="Returning JSON from a ZF2 controller action" href="http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/">
<link rel="next" title="Access view variables in another view model" href="http://akrabat.com/zend-framework-2/access-view-variables-in-another-view-model/">
<meta name="generator" content="WordPress 3.5.1">
<link rel="canonical" href="http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/">
<link rel="shortlink" href="http://akrabat.com/2197">
<link rel="payment" type="text/html" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework-2%2Freturning-json-using-the-accept-header-in-zf2%2F&amp;language=en_GB&amp;category=text&amp;title=Returning+JSON+using+the+Accept+header+in+ZF2&amp;description=Developing+PHP+software+in+the+Real+World%2C+by+Rob+Allen&amp;tags=blog">

<link rel="openid.server" href="http://www.myopenid.com/server">
<link rel="openid.delegate" href="http://akrabat.myopenid.com/">

</head>
<body data-twttr-rendered="true">
<div id="page">


<div id="header">
	<div id="headerimg">
		<h1><a href="http://akrabat.com/">Rob Allen's DevNotes</a></h1>
		<div class="description">Developing PHP software in the Real World, by Rob Allen</div>
	</div>
	<ul class="topnav">
		<li><a href="http://akrabat.com/">Home</a></li>
		<li><a href="http://akrabat.com/zend-framework-2-tutorial/">ZF2 tutorial</a></li>
		<li><a href="http://akrabat.com/zend-framework-tutorial/">ZF1 tutorial</a></li>
		<li><a href="http://akrabat.com/talks/">Talks</a></li>
		<li><a href="http://akrabat.com/archives/">Archives</a></li>
		<li><a href="http://akrabat.com/about/">About</a></li>
	</ul>
</div>
<div id="container">
	<div id="content" class="column">
    <div id="pad">

  		<div class="navigation">
			<div class="alignleft">« <a href="http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/" rel="prev">Returning JSON from a ZF2 controller action</a></div>
			<div class="alignright"><a href="http://akrabat.com/zend-framework-2/access-view-variables-in-another-view-model/" rel="next">Access view variables in another view model</a> »</div>
		</div>

		<div class="post " id="post-2197">
			<h2><a href="http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/" rel="bookmark" title="Permanent Link: Returning JSON using the Accept header in ZF2">Returning JSON using the Accept header in ZF2</a></h2>

			<div class="entry">
				<p><strong>2 December 2012: Note that as of ZF2.0.4, this no longer works due to changes to fix a security issue. See the <a href="http://framework.zend.com/blog/zend-framework-2-0-4-released.html">release notes</a> for further information.</strong></p>
<p>Following yesterday's article on <a href="http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/">returning JSON from a ZF2 controller action</a>, <a href="http://twitter.com/lsmith">Lukas</a> suggested that I should also demonstrate how to use the Accept header to get JSON. So this is how you do it!</p>
<h3>Set up the JsonStrategy</h3>
<p>We set up the <tt>JsonStrategy</tt> as we did in <a href="http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/">returning JSON from a ZF2 controller action</a>.</p>
<h3>Return a ViewModel from the controller</h3>
<p>As we're letting the <tt>JsonStrategy</tt> intercede for us, we don't need to do anything special in our controller at all. In this case, we simply return a normal <tt>ViewModel</tt> for use by either the <tt>JsonRenderer</tt> or <tt>PhpRenderer</tt> as required:</p>
<p><strong>module/Application/src/Application/Controller/IndexController.php:</strong></p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="php"><pre class="de1"><span class="kw2">namespace</span> Application\Controller<span class="sy0">;</span>
&nbsp;
<span class="kw2">use</span> Zend\Mvc\Controller\ActionController<span class="sy0">,</span>
    Zend\View\Model\ViewModel<span class="sy0">;</span>
&nbsp;
<span class="kw2">class</span> IndexController <span class="kw2">extends</span> ActionController
<span class="br0">{</span>
    <span class="kw2">public</span> <span class="kw2">function</span> anotherAction<span class="br0">(</span><span class="br0">)</span>
    <span class="br0">{</span>
        <span class="re0">$matches</span><span class="br0">[</span><span class="br0">]</span> <span class="sy0">=</span> <span class="kw3">array</span><span class="br0">(</span><span class="st_h">'distance'</span> <span class="sy0">=&amp;</span>gt<span class="sy0">;</span> <span class="nu0">10</span><span class="sy0">,</span> <span class="st_h">'playground'</span> <span class="sy0">=&amp;</span>gt<span class="sy0">;</span> <span class="kw3">array</span><span class="br0">(</span><span class="st_h">'a'</span><span class="sy0">=&amp;</span>gt<span class="sy0">;</span><span class="nu0">1</span><span class="br0">)</span><span class="br0">)</span><span class="sy0">;</span>
        <span class="re0">$matches</span><span class="br0">[</span><span class="br0">]</span> <span class="sy0">=</span> <span class="kw3">array</span><span class="br0">(</span><span class="st_h">'distance'</span> <span class="sy0">=&amp;</span>gt<span class="sy0">;</span> <span class="nu0">20</span><span class="sy0">,</span> <span class="st_h">'playground'</span> <span class="sy0">=&amp;</span>gt<span class="sy0">;</span> <span class="kw3">array</span><span class="br0">(</span><span class="st_h">'a'</span><span class="sy0">=&amp;</span>gt<span class="sy0">;</span><span class="nu0">2</span><span class="br0">)</span><span class="br0">)</span><span class="sy0">;</span>
        <span class="re0">$matches</span><span class="br0">[</span><span class="br0">]</span> <span class="sy0">=</span> <span class="kw3">array</span><span class="br0">(</span><span class="st_h">'distance'</span> <span class="sy0">=&amp;</span>gt<span class="sy0">;</span> <span class="nu0">30</span><span class="sy0">,</span> <span class="st_h">'playground'</span> <span class="sy0">=&amp;</span>gt<span class="sy0">;</span> <span class="kw3">array</span><span class="br0">(</span><span class="st_h">'a'</span><span class="sy0">=&amp;</span>gt<span class="sy0">;</span><span class="nu0">3</span><span class="br0">)</span><span class="br0">)</span><span class="sy0">;</span>
&nbsp;
        <span class="re0">$result</span> <span class="sy0">=</span> <span class="kw2">new</span> ViewModel<span class="br0">(</span><span class="kw3">array</span><span class="br0">(</span>
            <span class="st_h">'success'</span><span class="sy0">=&amp;</span>gt<span class="sy0">;</span><span class="kw4">true</span><span class="sy0">,</span>
            <span class="st_h">'results'</span> <span class="sy0">=&amp;</span>gt<span class="sy0">;</span> <span class="re0">$matches</span><span class="sy0">,</span>
        <span class="br0">)</span><span class="br0">)</span><span class="sy0">;</span>
        <span class="kw1">return</span> <span class="re0">$result</span><span class="sy0">;</span>
    <span class="br0">}</span>
<span class="br0">}</span></pre></div></div></div></div></div></div></div>


<p>with our HTML view script:</p>
<p><strong>module/Application/view/index/another.phtml:</strong></p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="php"><pre class="de1"><span class="sy0">&lt;</span> ?php <span class="kw1">if</span> <span class="br0">(</span><span class="re0">$success</span><span class="br0">)</span><span class="sy0">:</span> <span class="sy1">?&gt;</span>
&nbsp;
<span class="sy0">&lt;</span>h2<span class="sy0">&gt;</span>Results<span class="sy0">&lt;/</span>h2<span class="sy0">&gt;</span>
&nbsp;
<span class="sy0">&lt;</span>ul<span class="sy0">&gt;</span>
 <span class="sy0">&lt;</span> ?php <span class="kw1">foreach</span> <span class="br0">(</span><span class="re0">$results</span> <span class="kw1">as</span> <span class="re0">$row</span><span class="br0">)</span><span class="sy0">:</span> <span class="sy1">?&gt;</span>
    <span class="sy0">&lt;</span>li<span class="sy0">&gt;</span>Distance<span class="sy0">:</span> <span class="sy0">&lt;</span> ?php <span class="kw1">echo</span> <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">escape</span><span class="br0">(</span><span class="re0">$row</span><span class="br0">[</span><span class="st_h">'distance'</span><span class="br0">]</span><span class="br0">)</span><span class="sy0">;</span><span class="sy1">?&gt;</span>m<span class="sy0">&lt;/</span>li<span class="sy0">&gt;</span>
<span class="sy0">&lt;</span> ?php <span class="kw1">endforeach</span><span class="sy0">;</span> <span class="sy1">?&gt;</span>
<span class="sy0">&lt;/</span>ul<span class="sy0">&gt;</span>
&nbsp;
<span class="sy0">&lt;</span> ?php <span class="kw1">endif</span><span class="sy0">;</span> <span class="sy1">?&gt;</span></pre></div></div></div></div></div></div></div>


<p>So if you set up a route and browse to it, you'll see a nicely rendered page.</p>
<h3>Retrieving the data as JSON</h3>
<p>To retrieve the data via JSON, we need a client where we can set the Accept header. We'll use <tt>curl</tt> for this test. When doing anything with APIs and testing, we head over to <a href="http://twitter.com/lornajane">LornaJane</a>'s blog for the <a href="http://www.lornajane.net/posts/2008/Curl-Cheat-Sheet">Curl Cheat Sheet</a> and use this command line:</p>
<pre>curl -H "Accept: application/json" http://zf2test.dev/json/another
</pre>
<p>and you should see the output of:</p>
<pre>{
  "content":{
    "success":true,
    "results": [
      {"distance":10,"playground":{"a":1}},
      {"distance":20,"playground":{"a":2}},
      {"distance":30,"playground":{"a":3}}
    ]
  }
}
</pre>
<p>(Formatted for readability - you get the result back on a single line from <tt>curl</tt>.)</p>
<p>This way you can use the same controllers for your HTML views and for returning JSON to those clients that can use it.</p>

				
                <div class="social">
                    <span>Like this article? </span>
                    <ul>
                        <li><a href="http://akrabat.com/?flattrss_redirect&amp;id=2197&amp;md5=96ea55c57fca93c49f1f14e1104716a7" title="Flattr" target="_blank"><img src="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/flattr-badge-large.png" alt="flattr this!"></a></li>
                        <li><iframe data-twttr-rendered="true" title="Twitter Tweet Button" style="width: 55px; height: 20px;" class="twitter-share-button twitter-count-none" src="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/tweet_button.html" allowtransparency="true" frameborder="0" scrolling="no"></iframe><script src="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/ga.js" async="" type="text/javascript"></script><script type="text/javascript" src="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/widgets.js"></script></li>

                    </ul>
                </div>

				<p class="postmetadata alt">
					<small>
						This entry was posted
												on Friday, 30th March 2012 at 08:16						and is filed under <a href="http://akrabat.com/category/zend-framework-2/" title="View all posts in Zend Framework 2" rel="category tag">Zend Framework 2</a>.
												
					</small>
				</p>

			</div>
		</div>

	
<!-- You can start editing here. -->


  		<!-- If comments are closed. -->
			    	    
	


	
	</div>
	</div>
	<div id="sidebar" class="column">
		<ul>

			<li>
				<form method="get" id="searchform" action="http://akrabat.com/">
<div><input name="s" id="s" type="text">
<input id="searchsubmit" value="Search" type="submit">
</div>
</form>
			</li>
                        <li style="margin-top: 10px;">
                           <a href="http://itunes.apple.com/app/daily-jotter/id411293034?mt=12" title="">
 <img src="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/dj-banner-150.jpg" alt="Daily Jotter on iTunes" border="0" height="225" width="150"></a>
                        </li>
                        <li style="margin-top: 10px;">
                           <p style="margin-bottom: 3px;">My <a href="http://www.zendframeworkinaction.com/">Zend Framework Book</a>:</p>
                           <a href="http://www.zendframeworkinaction.com/" title="">
 <img src="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/allen_cover150.jpg" alt="Zend Framework in Action cover" border="0" height="188" width="150"></a>
                        </li>
			<li><h2>Rob Allen</h2>
			<p>
Rob is a PHP and Zend Framework expert based in Worcester, UK. He is the Technical Director for <a href="http://www.bigroominternet.co.uk/">Big Room Internet</a> and the author of <a href="http://www.zendframeworkinaction.com/">Zend Framework in Action</a>.</p>
<p>He also supports the <a href="http://www.cahp.girl-wonder.org/">Con Anti-Harrassment Project</a>.</p>
<p>Around the web:<br>
Twitter: <a href="http://www.twitter.com/akrabat">@akrabat</a><br>
Flickr: <a href="http://www.flickr.com/photos/akrabat">photos</a><br>
Linked in: <a href="http://uk.linkedin.com/in/akrabat">profile</a><br>
</p>

			</li>

                        <li style="margin-top: 10px;">
                           
                           <a href="http://www.zend.com/en/services/certification/framework/education-advisory-board-zf" title="">
 <img src="Returning%20JSON%20using%20the%20Accept%20header%20in%20ZF2%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/ZF-Education-Advisory-Board-S.png" alt="Zend Framework Education Advisory Board Member" border="0" height="35" width="155"></a>
                        </li>

			<li class="pagenav"><h2>Other pages</h2><ul><li class="page_item page-item-95"><a href="http://akrabat.com/akras-diary/">Akra's Diary</a></li>
<li class="page_item page-item-1739"><a href="http://akrabat.com/disclosure-policy/">Disclosure policy</a></li>
<li class="page_item page-item-18"><a href="http://akrabat.com/dynamic-javascript-tabs/">Dynamic JavaScript Tabs</a></li>
<li class="page_item page-item-2066"><a href="http://akrabat.com/license-for-code-published-on-this-site/">License for code on this site</a></li>
<li class="page_item page-item-459"><a href="http://akrabat.com/shorter-links/">Shorter Links WP plugin</a></li>
</ul></li>


			
		</ul>
	</div>
</div>
<div id="footer-wrapper">
<div id="footer">
	<p style="float: right">Copyright © 2005-2013 Rob Allen. All rights reserved.</p>
	<p>
		<a href="http://akrabat.com/disclosure-policy/">Disclosure policy</a>
		| <a href="http://akrabat.com/license-for-code-published-on-this-site/">License for code on this site</a>
		| <a href="feed:http://akrabat.com/feed/">Entries RSS</a>
		| <a href="feed:http://akrabat.com/comments/feed/">Comments</a>
		<!-- 26 queries. 0.403 seconds. -->
		
	</p>
</div>
</div>
</div>


<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-365662-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>







</body></html>
<!-- Dynamic page generated in 0.392 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2013-05-03 15:32:48 -->
<!-- super cache -->